/******************************************************************************\
    KMP.cpp contains functions for the Knuth-Morris-Pratt algorithm.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#include "KMP.h"
#include <ctype.h>

void PreKMP( const char *str, int str_length, int *next )
{
	int i, j;

	i = 0;
	j = next[ 0 ] = -1;
	while( i < str_length )
	{
		while( j >= 0 && str[ j ] != str[ i ] )
			j = next[ j ];
		++i;
		++j;
		if( str[ i ] == str[ j ] )
			next[ i ] = next[ j ];
		else
			next[ i ] = j;
	}
}

int KMP( const char *str, int str_length, const char *substr, int substr_length, const int *next )
{
	int i, j;

	i = j = 0;
	while( i < str_length )
	{
		while( j >= 0 && str[ i ] != substr[ j ] )
			j = next[ j ];
		++i;
		++j;
		if( j >= substr_length )
			return i - j;
	}
	return -1;
}

void PreCIKMP( const char *str, int str_length, int *next )
{
	int i, j;

	i = 0;
	j = next[ 0 ] = -1;
	while( i < str_length )
	{
		while( j >= 0 && tolower( ( int )( unsigned )( unsigned char )str[ j ] ) != tolower( ( int )( unsigned )( unsigned char )str[ i ] ) )
			j = next[ j ];
		++i;
		++j;
		if( tolower( ( int )( unsigned )( unsigned char )str[ i ] ) == tolower( ( int )( unsigned )( unsigned char )str[ j ] ) )
			next[ i ] = next[ j ];
		else
			next[ i ] = j;
	}
}

int CIKMP( const char *str, int str_length, const char *substr, int substr_length, const int *next )
{
	int i, j;

	i = j = 0;
	while( i < str_length )
	{
		while( j >= 0 && tolower( ( int )( unsigned )( unsigned char )str[ i ] ) != tolower( ( int )( unsigned )( unsigned char )substr[ j ] ) )
			j = next[ j ];
		++i;
		++j;
		if( j >= substr_length )
			return i - j;
	}
	return -1;
}
